package com.zrkizzy.module.content.service.article;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrkizzy.common.core.utils.IdUtil;
import com.zrkizzy.common.models.domain.blog.category.ArticleCategory;
import com.zrkizzy.content.facade.service.article.IArticleCategoryService;
import com.zrkizzy.module.content.mapper.article.ArticleCategoryMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文章分类关联业务逻辑接口实现类
 *
 * @author zhangrongkang
 * @since 2023/10/7
 */
@Slf4j
@Service
public class ArticleCategoryServiceImpl implements IArticleCategoryService {

    @Autowired
    private IdUtil idUtil;

    @Autowired
    private ArticleCategoryMapper articleCategoryMapper;

    /**
     * 关联文章与分类
     *
     * @param articleId  文章ID
     * @param categoryId 分类ID
     * @return 是否关联成功
     */
    @Override
    public Boolean insert(Long articleId, Long categoryId) {
        return articleCategoryMapper.insert(ArticleCategory.builder().id(idUtil.nextId()).articleId(articleId).categoryId(categoryId).build()) == 1;
    }

    /**
     * 根据文章ID获取分类ID
     *
     * @param articleId 文章ID
     * @return 分类ID
     */
    @Override
    public Long getCategoryIdByArticleId(Long articleId) {
        return articleCategoryMapper.getCategoryIdByArticleId(articleId);
    }

    /**
     * 根据文章ID获取文章分类关联对象
     *
     * @param articleId 文章ID
     * @return 文章分类关联对象
     */
    @Override
    public ArticleCategory getByArticleId(Long articleId) {
        // 定义查询对象
        QueryWrapper<ArticleCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", articleId);
        // 查询并返回结果
        return articleCategoryMapper.selectOne(queryWrapper);
    }

    /**
     * 更新文章分类
     *
     * @param articleCategory 文章分类关联对象
     * @return 是否更新成功
     */
    @Override
    public Boolean update(ArticleCategory articleCategory) {
        // 更新并返回结果
        return articleCategoryMapper.updateById(articleCategory) == 1;
    }

    /**
     * 删除文章分类关联数据
     *
     * @param articleId 文章ID
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByArticleId(Long articleId) {
        QueryWrapper<ArticleCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", articleId);
        // 查询关联数量
        Long count = articleCategoryMapper.selectCount(queryWrapper);
        // 比较受影响行数来判断是否删除成功
        return articleCategoryMapper.delete(queryWrapper) == count;
    }
}
